package com.github.bluesbruce.mqtt.web;

import com.github.bluesbruce.mqtt.sender.IMqttSender;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * MQTT消息发送
 *
 * @author BBF
 */
@Controller
@RequestMapping(value = "/")
public class MqttController {

  private static final Logger LOGGER = LoggerFactory.getLogger(MqttController.class);
  /**
   * 注入发送MQTT的Bean
   */
  @Resource
  private IMqttSender iMqttSender;

  @ResponseBody
  @GetMapping(value = {"/", "index", "/index.html"}, produces = MediaType.TEXT_HTML_VALUE)
  public void index(HttpServletResponse response) throws IOException {
    response.sendRedirect("/static/websocket/index.html");
  }

  /**
   * 发送MQTT消息
   *
   * @param message 消息内容
   * @return 返回
   */
  @ResponseBody
  @PostMapping(value = "/mqtt", produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<String> sendMqtt(@RequestParam(value = "msg") String message) {
    LOGGER.info("================生产MQTT消息===={}============", message);
    iMqttSender.sendToMqtt(message);
    return new ResponseEntity<>("OK", HttpStatus.OK);
  }


  /**
   * 发送MQTT消息
   *
   * @param message 消息内容
   * @return 返回
   */
  @ResponseBody
  @PostMapping(value = "/mqtt2", produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<String> sendMqtt2(@RequestParam(value = "msg") String message) {
    LOGGER.info("================生产MQTT2消息===={}============", message);
    iMqttSender.sendToMqtt("hello", message);
    return new ResponseEntity<>("OK", HttpStatus.OK);
  }
}
